package org.example.sensor.service;

import lombok.RequiredArgsConstructor;
import org.example.sensor.dto.ChatMessage;
import org.example.sensor.dto.ChatRequest;
import org.example.sensor.dto.ChatResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SparkService {

    @Value("${spark.api.key}")
    private String apiKey;

    private final String SPARK_URL = "https://spark-api-open.xf-yun.com/v1/chat/completions";

    public ChatResponse sendMessage(ChatRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构造符合API规范的请求体
        Map<String, Object> body = new HashMap<>();
        body.put("model", request.getModel());
        body.put("messages", request.getMessages());
        for (ChatMessage chatMessage : request.getMessages()) {
            System.out.println(chatMessage);
        }
        body.put("temperature", 0.5);

        RestTemplate restTemplate = new RestTemplate();
        // 发送请求
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        return restTemplate.postForObject(SPARK_URL, entity, ChatResponse.class);
    }
}